package com.zhengyisky.controller;

import com.alibaba.fastjson.JSONObject;
import com.zhengyisky.entity.User;
import com.zhengyisky.service.UserService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
public class BaiduController {

    @Autowired
    private UserService userService;
    
    @Value("${baidu.apiKey}")
    private String apiKey;
    
    @Value("${baidu.secretKey}")
    private String secretKey;

    @Value("${baidu.redirectUri}")
    private String redirectUri;

    @RequestMapping("/baidu")
    public String baidu(String code) throws IOException {
        //接收code授权码后，用code换取用户的信息
        String tokenUrl = "https://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&code="+code+"&client_id="+apiKey+"&client_secret="+secretKey+"&redirect_uri="+redirectUri;
        HttpClient httpClient = HttpClients.createDefault();
        HttpGet get = new HttpGet(tokenUrl);
        HttpResponse response = httpClient.execute(get);
        String json = EntityUtils.toString(response.getEntity(), "UTF-8");
        System.out.println(json);
        Map tokenResult = JSONObject.parseObject(json, Map.class);
        String access_token = (String) tokenResult.get("access_token");
        //根据token获取用户信息
        String infoUrl = "https://openapi.baidu.com/rest/2.0/passport/users/getLoggedInUser";
        HttpPost post = new HttpPost(infoUrl);
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("access_token",access_token));
        //表单数据UrlEncodedFormEntity   JSON数据StringEntity
        HttpEntity entity = new UrlEncodedFormEntity(list);
        post.setEntity(entity);
        response  = httpClient.execute(post);
        json = EntityUtils.toString(response.getEntity(), "UTF-8");
        Map infoResult = JSONObject.parseObject(json, Map.class);
        String baiduId = (String) infoResult.get("uid");

        System.out.println(baiduId);

        //根据baiduId查询用户表，判断是否有关联的账号
        User user = userService.findUserByOpenid(baiduId);
        if(user==null){
            //没有关联的账号
            return "redirect:bind.html?openid="+baiduId;
        }else{
            //有关联账号
            return "redirect:loading.html?mobile="+user.getPhone();
        }

    }

    @RequestMapping("/bind/{flag}")
    @ResponseBody
    public Boolean bind(@PathVariable Integer flag, @RequestBody User user) {
        if(flag==1){
            //已有账号
            return userService.haveAccount(user);
        }else{
            //没有账号
            return userService.noAccount(user);
        }
    }
}
